package com.fzj.charging.device.dao.repository.impl;

import com.fzj.charging.device.dao.repository.StationRedisRepository;
import com.fzj.charging.device.pojo.entity.ChargingStation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Repository("geoGeo")
public class StationRedisRepositoryImpl implements StationRedisRepository {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveStationLocation(List<ChargingStation> chargingStationList) {
        HashMap<ChargingStation, Point> hashMap = new HashMap<>();
        if(chargingStationList!=null&&!chargingStationList.isEmpty()){
            for(ChargingStation chargingStation : chargingStationList){
                Double stationLng = Double.valueOf(String.valueOf(chargingStation.getStationLng()));
                Double stationLat = Double.valueOf(String.valueOf(chargingStation.getStationLat()));
                Point point = new Point(stationLng, stationLat);
                hashMap.put(chargingStation,point);
            }
        }
        //定义geo的operations 同时绑定key
        BoundGeoOperations stationLocation = redisTemplate.boundGeoOps("station");
        //批量保存位置信息和场站信息到redis-geo
        stationLocation.add(hashMap);


    }

    @Override
    public List<ChargingStation> selectStation(Double lng, Double lat, Double distance) {
        ArrayList<ChargingStation> stationArrayList = new ArrayList<>();

        Circle circle = getCircle(lng, lat, distance);
        GeoResults<RedisGeoCommands.GeoLocation<ChargingStation>> stationList = redisTemplate.boundGeoOps("station").radius(circle);
        for (GeoResult<RedisGeoCommands.GeoLocation<ChargingStation>> locationGeoResult : stationList) {
            RedisGeoCommands.GeoLocation<ChargingStation> content = locationGeoResult.getContent();
            ChargingStation name = content.getName();
            stationArrayList.add(name);
        }

        return stationArrayList;
    }
    public Circle getCircle(Double lng, Double lat, Double distance){
        Point point = new Point(lng, lat);
        Distance geoDistance = new Distance(distance, Metrics.KILOMETERS);
        return new Circle(point, geoDistance);
    }
}
